package com.atguigu.sparsearray;

/**
 * 二维数组与稀疏数组的转换
 */
public class SparseArray {
    public static void main(String[] args) {
        //定义二维数组
        //设想是一个棋盘 蓝子为1 红子为2 空为0
        int[][] sparseArray = new int[11][11];
        //棋盘赋值
        sparseArray[3][2] = 5;
        sparseArray[2][6] = 7;

        System.out.println("原始二维数组");

        //遍历棋盘
        for (int[] rows : sparseArray) {
            for (int data: rows){
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }


        //创建计数器,记录二维数组的有效数据
        int sum = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (sparseArray[i][j]!=0){
                    sum ++;
                }
            }
        }
        //创建稀疏数组
        int[][] sparseArray2 = new int[sum+1][3];
        sparseArray2[0][0] = 11;
        sparseArray2[0][1] = 11;
        sparseArray2[0][2] = sum;
        //给稀疏数组赋值
        int count = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (sparseArray[i][j]!=0){
                    count++;
                    sparseArray2[count][0] = i;
                    sparseArray2[count][1] = j;
                    sparseArray2[count][2] = sparseArray[i][j];
                }
            }
        }

        System.out.println();
        System.out.println("稀疏数组");
        for (int i = 0; i < sparseArray2.length; i++) {
            System.out.printf("%d\t%d\t%d\t\n", sparseArray2[i][0], sparseArray2[i][1], sparseArray2[i][2]);
        }
        System.out.println();

       //创建二维数组
        int[][] chessArr = new int[sparseArray2[0][0]][sparseArray2[0][1]];
        //给二维数组赋值
        for (int i = 1; i < sparseArray2.length; i++) {
            chessArr[sparseArray2[i][0]][sparseArray2[i][1]] = sparseArray2[i][2];
        }

        System.out.println("还原后的二维数组~~~");
        for (int[] rows : chessArr) {
            for (int data: rows){
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
    }
}
